package com.phospherus.customerinfo.controller;

import com.phospherus.common.controller.BaseController;
import com.phospherus.common.controller.handler.ResultHandler;
import com.phospherus.customerinfo.entity.Customer;
import com.phospherus.customerinfo.service.ICustomerService;
import com.phospherus.user.entity.RoleUser;
import com.phospherus.user.entity.User;
import com.phospherus.user.service.RoleUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author songjinlong
 * @version 1.0
 * @since 2017/11/30
 */
@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController<Customer, ICustomerService> {
    @Autowired
    private RoleUserService roleUserService;

    @RequestMapping("/delete")
    @ResponseBody
    public ResultHandler delete(Long id){
        service.delete(id);
        return new ResultHandler(ResultHandler.SystemMessage.SUCCESS);
    }

    @Override
    protected boolean onBeforeQuery(Map<String, String> param, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("USER");
        if(user==null){
            throw new RuntimeException("用户未登陆");
        }
        RoleUser roleUser = roleUserService.getRoleUserByRoleIdAndUserId(5, user.getId());
        //风控员不做创建人过滤
        if (roleUser == null) {
            param.put("createUserId", user.getId().toString());
        }
        return super.onBeforeQuery(param, request);
    }

    @RequestMapping(value = "/save", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResultHandler<Customer> save(Customer customer, HttpServletRequest request) {
        String message = service.check(customer);
        if (StringUtils.isBlank(message)) {
            User user = (User) request.getSession().getAttribute("USER");
            if (user != null) {
                customer.setCreateUserId(user.getId());
                customer.setCreateUserName(user.getUserName());
                return new ResultHandler(ResultHandler.SystemMessage.SUCCESS, service.save(customer));
            }else{
                message = "用户未登录";
            }
        }
        return new ResultHandler(0, message);
    }
}
